package com.douya.pangu.application.sys;

import cn.hutool.json.JSONUtil;
import com.douya.pangu.application.sys.pojo.dto.SocketDTO;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

/**
 * webSocket处理器
 *
 * @Author hcy
 * @Date 2023/3/23
 */
@Component
@Slf4j
public class PanGuWebSocketHandler extends TextWebSocketHandler {


    private static final Map<String, WebSocketSession> USER_MAP = Maps.newHashMap();

    /**
     * 连接建立后触发
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        // 获取session中的请求参数
        URI uri = session.getUri();
        if (uri == null) {
            return;
        }
        String query = uri.getQuery();
        String id = query.split("=")[1];
        // 上线后把数据库中的用户状态改为在线，并且发送之前离线的消息
        // userService.updateUserStatus(id, UserStatusEnum.ONLINE);
        // userService.sendOfflineMessage(id);
        USER_MAP.put(id, session);
        log.info("webSocket用户id:{},连接成功", id);
    }

    /**
     * 连接关闭后触发
     */
    @SuppressWarnings("NullableProblems")
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        // 从session中获取请求头信息
        URI uri = session.getUri();
        if (uri == null) {
            return;
        }
        String query = uri.getQuery();
        String id = query.split("=")[1];
        USER_MAP.remove(id);
        log.info("webSocket用户id:{},连接已断开", id);
    }

    /**
     * 给用户发送消息
     *
     * @param userId 用户id
     * @param socket 消息
     */
    public void sendByUser(Long userId, SocketDTO socket) {
        WebSocketSession webSocketSession = USER_MAP.get(String.valueOf(userId));
        if (webSocketSession != null && webSocketSession.isOpen()) {
            try {
                TextMessage message = new TextMessage(JSONUtil.toJsonStr(socket));
                webSocketSession.sendMessage(message);
            } catch (IOException e) {
                log.error("发送消息失败", e);
            }
        } else {
            // 如果用户不在线，将消息存入数据库
            log.info("用户不在线，将消息存入数据库");
            log.info("webSocket用户id:{},连接已断开", userId);
        }
    }

}
